import React, { Component, Suspense } from "react";
import { connect } from "dva";
import router from "umi/router";
import GridContent from "@/components/PageHeaderWrapper/GridContent";
import { FormattedMessage } from "umi-plugin-react/locale";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { List, Button, Icon, Card, Avatar, Form, Input, Modal, message, Upload, Select, Spin } from "antd";
import styles from "./index.less";
import Ellipsis from "@/components/Ellipsis";
import TypeNode from "../editDrawer/typeNode";
import UserSession from "@/UserSession";
import { routerRedux } from "dva/router";
import { doExportGraph, doImportGraph } from "@/services/knowledgegraph";
import ReferenceTemplate from '../tabCategory/referenceTemplate';

import graphImg from '@/assets/graph.png';
const { confirm } = Modal;
@connect(({ DialogList, loading }) => ({
	DialogList,
	loading: loading.models.data,
}))
class GraphList extends Component {
	state = {
		limit: 16,
		page: 1,
		list: [],
		total: 0,
		visible: false,
		type: "0",
		graphFile: null,
		createType: "1"
	};

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		};
		console.log(this.props);
	}

	fetchList() {
		const { limit, page } = this.state;
		this.props.fetchGraphListByPage(limit, page);
	}

	handleCreate() {
		const form = this.props.form;
		const { dispatch } = this.props;
		const { createType } = this.state;
		const that = this;
		form.validateFields((err, values) => {
			if (err) {
				return;
			};
			if (createType == 1) {
				dispatch({
					type: "knowledgeGraphList/addGraph",
					payload: { name: values.name, categoryId: values.graphCategoryId },
					callback: (res) => {
						if (typeof res.code !== 'undefined' && res.code !== 0) {
							// message["error"](`${res.message}`);
						} else {
							that.fetchList();
							form.resetFields();
							message.info(res.msg);
							that.setState({ visible: false, type: "0" });
						}
					},
				});
			} else {
				that.importGraph(values)
			}
		});
	}
	delGraph(id) {
		const { dispatch, list } = this.props;
		const { page } = this.state;
		const that = this;
		confirm({
			title: "删除知识导图",
			content: "确定要删除该知识导图吗？",
			okText: "确定",
			cancelText: "取消",
			onOk() {
				dispatch({
					type: "knowledgeGraphList/delGraph",
					payload: { id },
					callback: (res) => {
						message.info(res.msg);
						if (list.length === 1 && page >= 2) {
							that.setState({ page: page - 1 }, () => {
								that.fetchList();
							});
						} else {
							that.fetchList();
						}
					},
				});
			},
			onCancel() { },
		});
	}
	fixStatus(id, item) {
		const { dispatch } = this.props;
		const that = this;
		dispatch({
			type: "knowledgeGraphList/fixGraphStatus",
			payload: { id, disabled: item.disabled ? 0 : 1 },
			callback: (res) => {
				message.info(res.msg);
				that.fetchList();
			},
		});
	}
	fenye = (page) => {
		this.setState({ page }, () => {
			this.fetchList();
		});
	};
	addOrEdit(id, name) {
		const { location, pathId, dispatch } = this.props;
		let pathname = "";
		if (UserSession.isSystemKnowledge()) {
			pathname = "/knowledgeDesign/systemKnowledge/" + pathId + "/graph/edit";
		} else {
			pathname = "/knowledgeDesign/myKnowledge/" + pathId + "/graph/edit";
		};

		dispatch(
			routerRedux.push({
				pathname,
				query: { id, name, libraryQuery: location ? JSON.stringify(location.query) : null },
			})
		);
	}
	onTypeNode = (ref) => {
		this.TypeNode = ref;
	};

	infoChange = (info) => {
		let that = this;
		console.log(info);
		this.setState({
			graphFile: info.file
		})
	};

	changeType = (val) => {
		this.setState({ type: val });
	};

	downloadGraph = (id) => {
		const { dispatch } = this.props;

		dispatch({
			type: "knowledgeGraphList/get",
			payload: {
				atlasId: id,
				robotId: this.props.currentUser.tenantId,
			},
			callback: (res) => { },
		});
	};

	addKnowledgeGraph = () => {
		const { tabPaneList } = this.props;
		if (tabPaneList.length === 0) {
			return message.info("当前暂无分类，请先创建分类");
		};
		this.setState({ visible: true });
	};

	exportGraph = async item => {
		const res = await doExportGraph({ atlasId: item.id })
	}

	changeType = value => {
		this.setState({
			createType: value
		})
	}

	importGraph = async values => {
		const { graphFile } = this.state;
		if (!graphFile) {
			message.error('请上传文件')
			return false
		};
		const obj = new FormData()
		obj.append('file', graphFile)
		obj.append('atlasName', values.name)
		obj.append('categoryId', values.graphCategoryId)
		const res = await doImportGraph(obj)
		this.fetchList();
		this.props.form.resetFields();
		message.info(res.msg);
		this.cancelCreateModal()
	}

	cancelCreateModal = () => {
		this.setState({
			visible: false,
			createType: '1',
			graphFile: null,
			type: "0"
		})
	}

	reference = id => {
		if (this.referenceTemplateRef) {
			this.referenceTemplateRef.init({ type: null, id })
		}
	}

	render() {
		const { page, createType, graphFile } = this.state;
		const { getFieldDecorator } = this.props.form;
		const { tabPaneList, graphCategoryId, list, total, graphLoading, current } = this.props;
		const uploadProps = {
			name: "file",
			onChange: this.infoChange,
			showUploadList: false,
			accept: '.json',
			beforeUpload: () => { return false }
		};
		const formItemLayout = {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 6 },
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 16 },
			},
		};

		return (
			<Spin spinning={graphLoading}>
				<div className={styles.cardList}>
					{UserSession.isSystemKnowledge() ? null : (
						<div style={{ marginBottom: 16 }}>
							<Button type="primary" onClick={() => this.addKnowledgeGraph()}>新增</Button>
						</div>
					)}
					<List
						rowKey='id'
						pagination={{
							onChange: (page) => this.fenye(page),
							current: current,
							pageSize: 16,
							total: parseInt(total),
							showQuickJumper: true,
						}}
						grid={{ gutter: 24, lg: 4, md: 3, sm: 2, xs: 1 }}
						dataSource={list}
						renderItem={(item) => (
							<List.Item key={item._id}>
								<Card
									hoverable
									className={styles.card}
									actions={UserSession.isSystemKnowledge() ? [
										<a onClick={() => this.addOrEdit(item.id, item.name)}>查看</a>,
										<a onClick={() => this.reference(item.id)}>引用该模板</a>,
									] : UserSession.isAdmin() ? [
										<a onClick={() => this.delGraph(item.id)}>删除</a>,
										<a onClick={() => this.exportGraph(item)}>导出</a>,
										<a onClick={() => this.addOrEdit(item.id, item.name)}>进入</a>,
									] : [
										<a onClick={() => this.delGraph(item.id)}>删除</a>,
										<a onClick={() => this.fixStatus(item.id, item)}>
											{" "}{item.disabled ? ("启用") : ("停用")}{" "}
										</a>,
										<a onClick={() => this.exportGraph(item)}>导出</a>,
										<a onClick={() => this.addOrEdit(item.id, item.name)}>进入</a>,
									]}
								>
									<Card.Meta
										avatar={
											<Avatar className={styles.cardAvatar}>
												<img src={graphImg} style={{ width: '16px' }} />
											</Avatar>
										}
										title={<a>{item.name}</a>}
										description={
											UserSession.isSystemKnowledge() || UserSession.isAdmin() ? null : <Ellipsis
												className={styles.item}
												style={item.disabled ? {
													background: '#FF9640',
													borderColor: '#FF9640',
												} : {
													background: '#14C6A1',
													borderColor: '#14C6A1',
												}}
												lines={3}
											>
												{item.disabled ? (
													<span style={{ color: "#FFFFFF" }}>已停用</span>
												) : (
													<span style={{ color: "#FFFFFF" }}>启用中</span>
												)}
											</Ellipsis>
										}
									/>
								</Card>
							</List.Item>
						)}
					/>

					<ReferenceTemplate onRef={ref => this.referenceTemplateRef = ref} />

					<Modal
						visible={this.state.visible}
						title='新建知识导图'
						okText='确认'
						cancelText='取消'
						onCancel={this.cancelCreateModal}
						onOk={this.handleCreate.bind(this)}
						destroyOnClose
					>
						<Form {...formItemLayout}>
							<Form.Item label='知识导图名称'>
								{getFieldDecorator("name", {
									rules: [{ required: true, message: "知识导图名称必填" }],
								})(<Input onPressEnter={this.handleCreate.bind(this)} />)}
							</Form.Item>
							<Form.Item label='知识导图分类'>
								{getFieldDecorator("graphCategoryId", {
									rules: [{ required: true, message: "知识导图分类必填" }],
									initialValue: graphCategoryId,
								})(
									<Select>
										{tabPaneList.map((item) => {
											return (
												<Select.Option value={item.id} key={item.id}>
													{item.name}
												</Select.Option>
											);
										})}
									</Select>
								)}
							</Form.Item>
							<Form.Item label="新建方式">
								{
									getFieldDecorator("createType", {
										initialValue: createType
									})(
										<Select onChange={this.changeType}>
											<Select.Option value="1">直接创建</Select.Option>
											<Select.Option value="2">导入文件</Select.Option>
										</Select>
									)
								}
							</Form.Item>
							{
								createType == 2 ? (
									<Form.Item label="上传文件">
										{getFieldDecorator('uploadGraph')(
											<Upload {...uploadProps}>
												{
													graphFile ? graphFile.name : ''
												}
												<Button>
													<Icon type="upload" /> {graphFile ? '重新上传' : '上传文件'}
												</Button>
											</Upload>,
										)}
									</Form.Item>
								) : ''
							}

						</Form>
					</Modal>
				</div>
			</Spin>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(GraphList));
